import config from '@/config'
import storage from '@/common/storage'
import {
    LoginApi
} from '@/api/login-api.js'
import * as SSKEYS from '@/common/session-storage-keys.js'
import {
    getToken,
    setToken,
    removeToken
} from '@/common/auth'

import Chat from '../../common/chat.js'

const baseUrl = config.baseUrl

const user = {
    state: {
        token: getToken(),
        name: storage.get(SSKEYS.ACCOUNT_NAME_KEY),
        avatar: storage.get(SSKEYS.ACCOUNT_AVATAR_KEY),
        roles: storage.get(SSKEYS.ACCOUNT_ROLES_KEY),
        permissions: storage.get(SSKEYS.ACCOUNT_PERMISSIONS_KEY),

        chat: null,
        chatList: [], //会话列表
        totalNoreadnum:0, //未读消息总数角标
        totalPeopleNum:0, //未读人数
        chatDetail: [], //会话详情
        chatObj:{},//会话对象
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_NAME: (state, name) => {
            state.name = name
            storage.set(SSKEYS.ACCOUNT_NAME_KEY, name)
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
            storage.set(SSKEYS.ACCOUNT_AVATAR_KEY, avatar)
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
            storage.set(SSKEYS.ACCOUNT_ROLES_KEY, roles)
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions
            storage.set(SSKEYS.ACCOUNT_PERMISSIONS_KEY, permissions)
        },
        SET_CHAT: (state, chat) => {
            state.chat = chat
        },
        SET_CHATOBJ: (state, chatObj) => {
            state.chatObj = chatObj
        }
    },

    actions: {
        // 登录
        Login({
            commit
        }, userInfo) {
            const username = userInfo.username.trim()
            const password = userInfo.password
            return new Promise(async (resolve, reject) => {
                LoginApi.login(username, password).then(res => {
                    setToken(res.token)
                    commit('SET_TOKEN', res.token)
                    resolve(res)
                }).catch(error => {
                    resolve({
                        code: -1,
                        msg: error.message
                    })
                })
            })
         
        },
        initChat({state, dispatch}){
            const chat = new Chat({
                url: config.socketUrl
            })
            state.chat = chat
            if(state.chat){
                dispatch("getChatList")
                dispatch("updateBadge")
                dispatch("getChatDetail")
            }
        },
        initLogin({
            state,
            dispatch
        }) {
            const user = JSON.parse(uni.getStorageSync('user')) 
            if (user) {
                state.chat = new Chat({
                    url: config.socketUrl
                })
                dispatch("getChatList")
                dispatch("updateBadge")
                dispatch("getChatDetail")
            }
        },
        closeSocket({state}){
            if(state.chat){
                state.chat.close()
                state.chat = null
            }
        },
        getNoReadPeople({state, dispatch}){
             storage.get(``, permissions)
        },
        getChatList({
            state,
            dispatch
        }) {
            state.chatList = state.chat.getChatList()
            uni.$on("onUpdateChatList", (list) => {
                // console.log('getChatList======',list)
                state.chatList = list
            })
        },
        getChatDetail({
            state,
            dispatch
        }) {
            state.chatDetail = state.chat.getChatDetail()
            uni.$on("onUpdateChatDetail", (list) => {
                // console.log('onUpdateChatDetail======',list)
                state.chatDetail = list
            })
        },
        
        
        // 初始化总未读数角标
        updateBadge({
            state
        }) {
            // 开启监听总未读数变化
            uni.$on('totalNoreadnum', (num) => {
                state.totalNoreadnum = num
            })
            state.chat.updateBadge()
        },
        // 获取用户信息
        GetInfo({
            commit,
            state
        }) {
            return new Promise((resolve, reject) => {
                LoginApi.getInfo().then(res => {
                    const user = res.user
                    const avatar = (user == null || user.avatar == "" || user.avatar == null) ?
                        require("@/static/images/profile.jpg") : baseUrl + user.avatar
                    const username = (user == null || user.userName == "" || user.userName ==
                        null) ? "" : user.userName
                    if (res.roles && res.roles.length > 0) {
                        commit('SET_ROLES', res.roles)
                        commit('SET_PERMISSIONS', res.permissions)
                    } else {
                        commit('SET_ROLES', ['ROLE_DEFAULT'])
                    }
                    commit('SET_NAME', username)
                    commit('SET_AVATAR', avatar)
                    uni.setStorageSync('hospital', JSON.stringify(res.hospital))
                    console.log('------------------------res.hospital',res.hospital)
                    if(user.isPatient==2){
                        uni.setStorageSync('isPatientA', user.isPatient)
						if( uni.getStorageSync('isPatient')==0||uni.getStorageSync('isPatient')==''||uni.getStorageSync('isPatient')==undefined){
							uni.setStorageSync('isPatient', 0)
						}
                    }else{
						 uni.setStorageSync('isPatientA', user.isPatient)
						 uni.setStorageSync('isPatient', user.isPatient)
					}
                    uni.setStorageSync('user', JSON.stringify(res.user))
					
                    resolve(res)
                }).catch(error => {
                    resolve({
                        code: -1,
                        msg: error.message
                    })
                })
            })
        },

        // 退出系统
        LogOut({
            commit,
            state,
            dispatch
        }) {
            return new Promise((resolve, reject) => {
                LoginApi.logout().then((res) => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    commit('SET_PERMISSIONS', [])
                    commit('SET_CHAT', null)
                    commit('SET_CHATOBJ', {})
                    uni.removeStorageSync('user')
                    uni.removeStorageSync('hospital')
                    uni.removeStorageSync('isPatient')
                    uni.removeStorageSync('isPatientA')
                    uni.removeStorageSync("patientHospital")
                    uni.$off("onUpdateChatList")
                    uni.$off("onUpdateChatDetail")
                    uni.$off("totalNoreadnum")
                    removeToken()
                    storage.clean()
                    resolve(res)
                }).catch(error => {
                    reject({
                        code: -1,
                        msg: error.message
                    })
                })
            })
        }
    }
}

export default user
